<template>
    <div class="wrap">
        <img class="bg-img" src="../assets/routerBack/triangle.png">
        <el-page-header class="page-head" @back="toHome" content="人脸签到">
        </el-page-header>
        <video class="pic-video"
               id="video" width="320" height="320" autoplay></video>
        <canvas id="canvas" width="480" height="320" style="display: none;"></canvas>
        <img v-show="false" :src="imgUrl" id="img" width="480" height="320" style="margin-left: 20px;">
        <div class="tip">
            <div class="content">
                <el-tag type="info">
                    <i class="el-icon-info">Tip:</i>
                </el-tag>
                人脸比对过程中请摘下帽子口罩等物品,将脸对准框内进行比对,以免影响比对结果
            </div>
        </div>
    </div>
</template>

<script>
    import {clockByFace} from '@/utils/apis/face'

    export default {
        name: "FaceCheck",
        data() {
            return {
                imgUrl: '',
                File: '',
                mediaStreamTrack: '',
                context: ''
            }
        },
        mounted() {
            this.initCamera()
            setTimeout(() => {
                this.takePhoto()
                this.confirmSubmit()
            }, 3000)
            this.$message.info('三秒后开始对比人脸,请将人脸对齐框内')
        },
        destroyed() {
            this.closeVideo()
        },
        methods: {
            //初始化拍照
            initCamera() {
                let self = this
                navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia
                if (navigator.getUserMedia) {
                    //调用用户媒体设备, 访问摄像头
                    navigator.getUserMedia({video: {width: 480, height: 320}}, stream => {
                        this.mediaStreamTrack = stream
                        var video = document.querySelector('video');
                        video.srcObject = stream;
                        self.streamPicture = stream; //关闭摄像头需要用
                        video.onloadedmetadata = function (e) {
                            video.play();
                        }
                    }, error => {
                        self.$message.error('访问用户媒体设备失败:' + error.name)
                    })
                } else {
                    self.$message.error('不支持访问用户媒体');
                }

            },
            //拍照点击
            takePhoto() {
                let canvas = document.getElementById('canvas');
                let context = canvas.getContext('2d');
                this.context = context
                context.drawImage(video, 0, 0, 480, 320);
                // 获取图片base64链接
                var image = canvas.toDataURL('image/png');
                // 定义一个img
                var img = document.getElementById("img");
                //设置属性和src
                //img.id = "imgBoxxx";
                img.src = image;
                this.imgUrl = image
                // console.log(this.imgUrl)
                //将图片添加到页面中
                // document.body.appendChild(img);
                function dataURLtoFile(dataurl, filename) {
                    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                    while (n--) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    return new File([u8arr], filename, {type: mime});
                }

                this.File = dataURLtoFile(image, 'employee.png');
                return dataURLtoFile(image, 'employee.png');
            },
            //确认上传
            async confirmSubmit() {
                // debugger;
                if (this.File === '') { //如果不点击拍照
                    this.$message.warning(`请先拍照再点击确定`);
                    return;
                }
                const formData = {
                    file: this.File
                }
                try {
                    //发送网络请求
                    await clockByFace(formData).then(res => {
                        this.$message.success(res.data.data)
                        this.$confirm('是否继续进行其他人脸比对?', '操作提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'info'
                        }).then(() => {
                            this.$message.info('继续比对')
                            setTimeout(() => {
                                this.takePhoto()
                                this.confirmSubmit()
                            }, 3000)
                            this.$message.info('三秒后开始对比人脸,请将人脸对齐')
                        }).catch(() => {
                            this.$message.info('取消比对，返回上一页')
                            this.closeVideo()
                            this.$router.back()
                        })
                    })
                } catch (e) {
                    setTimeout(() => {
                        console.log('再次进行对比')
                        this.takePhoto()
                        this.confirmSubmit()
                        console.log("submitFinish!")
                    }, 1000)
                }

            },
            //返回上一页
            toHome() {
                this.closeVideo()
                this.$router.back()
            },
            closeVideo() {
                this.mediaStreamTrack.getVideoTracks().forEach(track => {
                    track.stop();
                });
            },
        }
    }
</script>

<style scoped>
    .wrap {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

    .bg-img {
        position: fixed;
        width: 100%;
        height: 100%;
        z-index: -1;
        top: 0;
        left: 0;
    }

    .page-head {
        position: fixed;
        top: 2%;
        left: 1%;
    }

    .pic-video {
        border-radius: 50%;
        object-fit: cover;
        box-shadow: rgba(0, 0, 0, 0.3) 1px 1px 10px;
    }

    .tip {
        margin-top: 3%;
        width: 80%;
        height: 10%;
    }

    .content {
        text-align: center;
    }
</style>